<template>
  <div>

    <main-layout>
      <div class="list-container">
        <auth-tag tips="无权访问">
        <vTable   
           ref="vGridTable"
          :columnsList="columnsList"
          apiUrl="boss/tanc_plantint_plan/list"
          :pageSize="15"
          :formConfig="formConfig"
          :toolbarConfig="false"
          @saveClick="goAddPopup"
          :queryData="{
            queryEntry:1,
            companyId:userStore.userInfo.companyId,
            farmId:userStore.userInfo.farmId }">

           <template #actions="{row}">
              <auth-tag code="8002">
                <el-button icon="view" class="btn-view" size="small" @click="goDetail(row.plantingPlanId)">详情</el-button>
              </auth-tag>
              <auth-tag code="8003">
                <el-button v-if="row.status=='DQR' || row.status=='ZXZ'" class="btn-eidt" icon="edit" size="small" :disabled="row.companyId != userStore.userInfo.companyId" @click="goAdd(row.plantingPlanId)">编辑</el-button>
              </auth-tag>
              <auth-tag code="8004">
                <el-button v-if="row.status=='DQR'" class="btn-del" style="color:#F56C6C" icon="delete" size="small" @click="del(row)">删除</el-button>
              </auth-tag>
            </template>
      </vTable>
      </auth-tag>
     </div>
      <c-dialog v-model:show="dialogVisible" v-if="dialogVisible" :showBtn="false" title="请选择创建种植方案"  :width="300">
        <div style="text-align:center;padding:20px 0">
        <el-button  size="small" icon="plus" style="width:200px"  @click="goAddUrl(1)">手动创建</el-button> <div style="height:10px" />
        <el-button  size="small" icon="position" :disabled="autoCreateTask" style="width:200px" type="primary" @click="goAddUrl(2)">获取方案</el-button>
      </div>
    </c-dialog>
    </main-layout>
  </div>
</template>

<script setup name="Manage-Plan-List">
import { ref, onMounted,computed } from 'vue'
import { useRouter } from 'vue-router'
import { getPlantList, delFarmPlant,getParamName} from '@/api/plant'
import mainLayout from '@/components/custom/mainLayout.vue'
import cTable from '@/components/custom/cTable.vue'
import cropSelect from '@/components/custom/cropSelect.vue'
import publicSelect from '@/components/custom/publicSelect.vue'
import cDialog from '@/components/custom/cDialog.vue'
import cropSeriesSelect from '@/components/custom/cropSeriesSelect.vue'
import { formatDateLongDD, formatDateDD } from '@/utils/format'
import { useUserStore } from '@/pinia/modules/user'
import { useFramStore } from '@/pinia/modules/farm'
import { message } from '@/utils/element'
import { ElMessageBox } from 'element-plus'
import delImg from '@/assets/del.png'
import { getUserList,getSelectList} from '@/api/select'

const router = useRouter()
const userStore = useUserStore()
const framStore = useFramStore()

onMounted(() => {
  getParamName('auto_create_task').then((res)=>{
    if(res.code===0){
      autoCreateTask.value = res.data.paramValue==1?false:true
    }
  })
  getUserSelectList()
})

  const getUserSelectList = async ()=>{
    userSelectList.value = await  getUserList({ page: 1, limit: 1000000, farmId: userStore.userInfo.farmId, companyId: userStore.userInfo.companyId})
    tillageWayList.value = await  getSelectList({ page: 1, limit: 1000000,lovCode: "TANC_TILLAGE_WAY"})
    cropList.value = await  getSelectList({ page: 1, limit: 1000000,lovCode:'TANC_CROP'})
  }

const getSeriesSelectList = async (cropId)=>{
    cropSeriesList.value = await  getSelectList({ page: 1, limit: 1000000,param1:cropId,lovCode:'TANC_ALL_SERIES'})
  }
const page = ref(1)
const autoCreateTask = ref(true)
const vGridTable = ref(null)
const dialogVisible = ref(false)
const cropSeriesIdValue = ref('')
const userSelectList = ref([])
const tillageWayList = ref([])
const cropList = ref([])
const cropSeriesList = ref([])

const refreshTable = () => {
  vGridTable.value.loadData()
}
const columnsList = ref([
      {field: 'number', title: '编号',minWidth:'90',align:'center'},
      {field: 'targetYield', title: '目标每亩产量(kg)',minWidth:'130',align:'center'},
      {field: 'totalLandArea', title: '地块面积(亩)',minWidth:'110',align:'center'},
      {field: 'cropName', title: '作物/品种',minWidth:'160',align:'center',slots:{
        default:({row})=>{
          return [row.cropName+' / '+row.cropSeriesName]
        }
      }},
      {field: 'tillageWayMeaning',minWidth:'110', title: '耕种方式',align:'center'},
      {field: 'startTime', title: '种植周期',align:'center',minWidth:'180',slots:{
        default:({row})=>{
          return [formatDateDD(row.planStartTime)+' ~ '+formatDateDD(row.planEndTime)]
        }
      }},
      {field: 'totalBudgetFee.standardString', minWidth:'110',title: '预算成本',align:'center'},
      {field: 'statusMeaning',minWidth:'110', title: '状态',align:'center', type:'html',
       formatter:({row})=>{
        if(row.status==='DQR'){
            return `<div style="color:#FF9C00;">${row.statusMeaning}</div>`
          }
        if(row.status==='ZXZ'){
            return `<div style="color:#4d70ff;">${row.statusMeaning}</div>`
          }
          if(row.status==='YWC'){
            return `<div style="color:#04AE70;">${row.statusMeaning}</div>`
          }
      },
    },
      {field: 'realName', title: '创建人',minWidth:'110',align:'center'},
      {field: 'createTime', title: '创建时间',minWidth:'160',align:'center'},
      {title: '操作', width: 240,fixed:'right', slots: {default: 'actions'}}
   ])

 const  formConfig = computed(
  ()=>{
  return {
      titleWidth: 100,
      titleAlign: 'center',
      items: [
      {
          field: 'cropId',
          title: '作物',
          span: 5,
          itemRender: {
            name: '$select',
            props: {
              placeholder: '请选择',
              clearable: true,
              options:cropList
            },
            events: { change: (row,data)=>{
              cropSeriesIdValue.value=''
              getSeriesSelectList(data.value)
            } },
          }
        },
        {
          field: 'cropSeriesId',
          title: '品种',
          span: 5,
          itemRender: {
            defaultValue:cropSeriesIdValue,
             content:cropSeriesIdValue,
            name: '$select',
            props: {
              placeholder: '请选择',
              clearable: true,
              options:cropSeriesList
            }
          }
        },
        {
          field: 'createId',
          title: '创建人',
          span: 5,
          itemRender: {
            name: '$select',
            props: {
              placeholder: '请选择',
              clearable: true,
              options:userSelectList
            }
          }
        },
        {
          field: 'statusList',
          title: '状态',
          span: 5,
          itemRender: {
            name: '$select',
            props: {
              placeholder: '请选择',
              clearable: true,
              multiple:true,
              options: [
                {label: '待确认', value: 'DQR'},
                {label: '执行中', value: 'ZXZ'},
                {label: '已完成', value: 'YWC'}
              ]
            }
          }
        },
        {
          field: 'tillageWayId',
          title: '耕种方式',
          span: 5,
          itemRender: {
            name: '$select',
            props: {
              placeholder: '请选择',
              clearable: true,
              options:tillageWayList
            }
          }
        },
        {
          field: 'dateRange',
          title: '创建时间',
          span: 5,
          slots: { default: 'dateRange' },
          itemRender: {}
        },
        {
          field: '',
          title: '',
          span: 5,
          className:'from-right-btn-add',
          showTitle:false,
          slots: { default: 'addButtom' }
        },
        {
          align: 'center', collapseNode: false,
          itemRender: {
            name: '$buttons',
            children: [
              {props: {type: 'submit', icon: 'vxe-icon-search', content: '查询', status: 'primary'}},
              {props: {type: 'reset', icon: 'vxe-icon-refresh', content: '重置'}}
            ]
          }
        }
      ]
  }

 }

  )

  
const del = (item) => {
  ElMessageBox.confirm('<div style="height:200px;width:100%;background-color:#f7f7f7;text-align: center;"><img style="padding:40px 0 0 0;height:40px" src="' + delImg + '" /> <div style="font-size: 16px;text-align: center;padding: 10px;font-weight: 600;">删除方案?</div><div style="font-size: 14px;text-align: center;color:#666">删除方案后无法恢复</div></div>', '删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      cancelButtonClass: 'cancelButtonClass',
      confirmButtonClass: 'confirmButtonClass',
      dangerouslyUseHTMLString: true,
      type: 'none',
    }
  ).then(async() => {
    const res = await delFarmPlant([item.plantingPlanId])
    if (res.code === 0 || res.success) {
      message('数据提交成功', 2)
      refreshTable()
    } else {
      message(res.message, 2)
    }
  })
}

const goAdd = async(id) => {
  framStore.set_backUrl('/manage/plan/list')
  if (id) {
    router.push(`/manage/plan/eidt?id=${id}`)
  } else {
    if(userStore.userInfo.userName == '17200000001'){
      router.push(`/manage/plan/create`)
    }else{
      router.push(`/manage/plan/add`)
    }
  }
}
const goAddPopup=async ()=>{
  dialogVisible.value = true
}
const goAddUrl=async (type)=>{
  dialogVisible.value = false
  if(type===1){
    router.push(`/manage/plan/add`)
  }else{
    router.push(`/manage/plan/create`)
  }
}


const goDetail = async(id) => {
  framStore.set_backUrl('/manage/plan/list')
  router.push(`/manage/plan/detail?plantHeaderId=${id}`)
}

</script>

<style>
.plan-daterange .el-range__icon{
   position: absolute;
    right: 0px;
    color: #04AE70;
    background: #f7f7f7;
    padding: 0 4px;
}
.plan-daterange .el-range__close-icon{
  right:20px;
}
.plan-daterange .el-range-input{
  padding-right: 30px;
}
</style>
<style lang="scss" scoped>
.list-container {
  box-sizing: border-box;
  height: calc(100vh - 120px);
}
.inputLine {
  display: flex;
  width: 300px;
  .zhi{
    padding: 0 10px;
  }
  s{
    font-style: normal;
    text-decoration: none;
    padding: 0 0 0 5px;
    color: var(--el-text-color-regular);
  }
}

</style>
